// 线性表 操作
// 线性表的顺序存储及其运算实现

#include "../constant.h"

typedef struct node
{
    DataType data[Capacity];
    int length;
} SeqList, *PSeqlist;

PSeqlist Init();
int Destory(PSeqlist L);
int Length(PSeqlist L);
int Locate(PSeqlist L, DataType x);
int Insert(PSeqlist L, DataType x);
int Insert(PSeqlist L, int i, DataType x);
int Delete(PSeqlist L, int i);
DataType GetItem(PSeqlist L, int i);
void printf(PSeqlist L);

// debug
int main()
{
    PSeqlist L = Init();
    for (int j = 0; j < 10; j++)
    {
        Insert(L, j);
    }
    Insert(L, 1, 11);
    printf(L);
    Delete(L, 2);
    printf(L);
    printf("第三个位置的数字是: %d\n", GetItem(L, 3));
    printf("数字2的位置是: %d\n", Locate(L, 2));
    printf("当前sequence list的长度是: %d\n", Length(L));

    Destory(L);

    return 0;
}

// The initialization of sequence list
PSeqlist Init()
{
    PSeqlist PL;
    PL = (PSeqlist)malloc(sizeof(SeqList));
    if (PL)
    {
        PL->length = 0;
        return PL;
    }
    else
    {
        printf("初始化线性表失败");
        return NULL;
    }
}

int Destory(PSeqlist L)
{
    if (L)
    {
        free(L);
    }
    return 1;
}

int Length(PSeqlist L)
{
    return L->length;
}

int Locate(PSeqlist L, DataType x)
{
    int i = 0;
    while (i < L->length && L->data[i] != x)
        i++;
    if (i >= L->length)
        return 0;
    else
        return i + 1;
}

int Insert(PSeqlist L, DataType x)
{
    return Insert(L, L->length + 1, x);
}

int Insert(PSeqlist L, int i, DataType x)
{
    if (!L)
    {
        printf("无效的线性表\n");
        return 0;
    }
    if (L->length >= Capacity)
    {
        printf("线性表已满\n");
        return 0;
    }
    if (i < 1 || i > L->length + 1)
    {
        printf("插入位置不合法\n");
        return 0;
    }
    for (int j = L->length; j > i - 1; j--)
    {
        L->data[j] = L->data[j - 1];
    }
    L->data[i - 1] = x;
    L->length++;
    return 1;
}

int Delete(PSeqlist L, int i)
{
    if (i > L->length)
    {
        printf("删除位置超出有效长度\n");
        return 0;
    }
    for (int j = i - 1; j < L->length - 1; j++)
    {
        L->data[j] = L->data[j + 1];
    }
    L->length--;
    return 1;
}

DataType GetItem(PSeqlist L, int i)
{
    if (i > L->length)
    {
        printf("索引越界\n");
        return 2147483647;
    }
    return L->data[i - 1];
}

void printf(PSeqlist L)
{
    printf("[");
    for (int j = 0; j < L->length; j++)
    {
        if (j != 0)
        {
            printf(", ");
        }
        printf("%d", L->data[j]);
    }
    printf("]\n");
}